package com.jinghaizhao.gqgl.spring.security;

import com.jinghaizhao.gqgl.mybatis.entity.PtUserEntity;
import com.jinghaizhao.gqgl.user.entity.SecurityUser;
import com.jinghaizhao.gqgl.user.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
class GqglUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        PtUserEntity ptUserEntity =  userService.queryUserInfoByName(username);
        if(ptUserEntity == null){
            throw  new IllegalArgumentException(username + " is not exit.");
        }

        String password = passwordEncoder.encode("123456");
        List<GrantedAuthority> collection = new ArrayList<>();
        collection.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        collection.add(new SimpleGrantedAuthority("ROLE_USER_UPDATE"));
        collection.add(new SimpleGrantedAuthority("ROLE_TEST1"));
        collection.add(new SimpleGrantedAuthority("ROLE_TEST1_ADD"));
        // 参数分别是：用户名，密码，用户权限
        SecurityUser user = new SecurityUser(username, ptUserEntity.getPassword(),ptUserEntity, collection);

        return user;
    }
}